package com.mcintyret.site.users;

import com.google.common.annotations.VisibleForTesting;
import com.mcintyret.site.security.PasswordEncrypter;
import com.mcintyret.site.security.GrantedAuthorityEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * User: mcintyret2
 * Date: 08/04/2012
 */

@Component
public class UserFactory {

    @Value("${password.encryption.enabled}")
    private boolean passwordEncryptionEnabled;
    @Resource
    private PasswordEncrypter passwordEncrypter;

    public User newNormalUser(String username, String password, String email) {
        return encryptPasswordIfEnabled(
                new User(username, password, email, GrantedAuthorityEnum.USER));
    }

    public User newAdminUser(String username, String password, String email) {
        return encryptPasswordIfEnabled(
                new User(username, password, email, GrantedAuthorityEnum.ADMIN));
    }

    private User encryptPasswordIfEnabled(User user) {
        if (passwordEncryptionEnabled) {
            passwordEncrypter.encryptUserPassword(user);
        }
        return user;
    }

    @VisibleForTesting
    void setPasswordEncryptionEnabled(boolean passwordEncryptionEnabled) {
        this.passwordEncryptionEnabled = passwordEncryptionEnabled;
    }
}
